package com.taptech.doufu.ui.fragment.NovelChildFragments;

import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.constant.SPKey;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.util.DensityUtil;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.SharedPreferencesKey;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.db.history.Read_HirstoryUtil;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.view.readview.PageFactory;
import com.taptech.doufu.ui.view.readview.util.CacheManager;
import com.taptech.doufu.services.GiftService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.ui.view.theme.read.ReadTheme;
import com.taptech.doufu.ui.view.theme.read.ReadThemeHelper;
import com.taptech.doufu.util.AesUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.MobileState;
import com.taptech.doufu.util.NoRepeatToast;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.ui.view.MyScrollView;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by op0509 on 2016/6/16.
 */
public class SectionDetailsFragment extends Fragment implements HttpResponseListener, View.OnClickListener, MyScrollView.OnScrollChangeListener, MyScrollView.OnScrollToBottomListener {
    private static final String ARG_SECTION_id = "section_id";
    private static final String ARG_NOVEL_ID = "novel_id";
    private static final String ARG_ARTICLE_ITEM = "article_item";
    private static final String ARG_ALL_PAGE = "all_page";
    private static final String ARG_OFFLINE = "offline";
    private static final String ARG_TOPIC = "topic";

    private RelativeLayout rlTop;// 顶部布局
    private TextView tvPageNumber;// 顶部页数显示及章节名显示

    public TextView getTvPageNumber() {
        return tvPageNumber;
    }

    public TextView getTvContent() {
        return tvContent;
    }

    private TextView tvContent;// 小说内容
    private ProgressBar progressBar;// 加载提示
    private RelativeLayout llLayout;
    private RelativeLayout rlPay;// 订阅布局
    private TextView tvTip;
    private Button btnPay;// 订阅按钮
    private LinearLayout llAutoPay;// 自动订阅布局
    private ImageView imgAutoPay;// 自动订阅图标
    private MyScrollView svLayout;// 滑动布局
    private View vsNotNetwork;// 无网布局
    private Button btnReload;// 重新下载
    private View viewClick;// 遮罩层，用于中部点击弹出导航栏
    private View viewNext;// 下滑区域
    private View viewPreview;// 上滑区域
    // pay dialog view
    private RelativeLayout payDialogLayout;
    private TextView payCancelBtn;
    private TextView jumpToPayBtn;
    private TextView payDesContentText;

    //底部状态
    private RelativeLayout rlBottomStatus;
    private ImageView ivMobileStatus;
    private ImageView ivCharger;
    private TextView tvTime;
    private TextView tvProgress;

    private String sectionId;// 章节id
    private String offlineData; //离线数据
    private String offlineTopicData;
    private String novelId;// 小说id
    private String articleTitle;// 章节title
    private String shareTitle;// 分享标题
    private String readID = "";
    private String setionTitle;// 章节名称
    private String des;// 章节内容
    private int articleNum;// 章节总数
    private int articleItem;// 当前页码
    private int allPage;// 总页数
    private int mFontSize;// 字体大小
    private int mScreenWidth;// 屏幕宽度
    private int mScreenHeight;// 屏幕高度
    private int width;
    private int height;
    private int nowY;// 目前所在Y轴上的点

    public void setNowY(int nowY) {
        this.nowY = nowY;
    }

    private boolean isOffLine = false;// 是否离线模式
    private boolean isYouthModel;

    public boolean isAutoPay() {
        return isAutoPay;
    }

    public void setAutoPay(boolean autoPay) {
        isAutoPay = autoPay;
    }

    private boolean isAutoPay = false;// 是否自动订阅
    public boolean isPay = true;// 是否已经付费过
    private boolean isLoginStateOld;// 记录获取数据时的登录状态
    private boolean isPaying = false;// 是否正在购买中
    private View lay;
    private HomeTopBean topicBean;

    public void setContentBean(HomeTopBean contentBean) {
        this.contentBean = contentBean;
    }

    private HomeTopBean contentBean;
    private TagsBean[] tagsBeans;
    private ImageView mRedPacket;
    private boolean isShowRedPacket = false;

    private JSONObject redPocketStr;
    private String  topicTitle;
    private LinearLayout llHelp;
    private ImageView ivHelp;

    private Read_HirstoryUtil mRead_HirstoryUtil;
    private SpannableString styledText;// 小说文本样式

    private NovelSectionDetailsActivity activity;

    private int indentType;

    public static SectionDetailsFragment newInstance(String sectionId, String novelId,String topic, int articleItem, int allPage){
        SectionDetailsFragment fragment = new SectionDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_SECTION_id, sectionId);
        bundle.putString(ARG_NOVEL_ID, novelId);
        bundle.putInt(ARG_ARTICLE_ITEM, articleItem);
        bundle.putInt(ARG_ALL_PAGE, allPage);
        if (!TextUtil.isEmpty(topic)) {
            bundle.putString(ARG_TOPIC,topic);

        }
        fragment.setArguments(bundle);
        return fragment;
    }

    public SectionDetailsFragment(){}

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.novel_details_list_item, container, false);
        activity = (NovelSectionDetailsActivity) getActivity();
        indentType = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_READ_INDENT,
                getActivity(), Constant.ReadIndentType.FORMAT);
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, getActivity(), "");
        if (pwd != null && pwd.length() > 0) {
            isYouthModel = true;
        }
        initUI(view);
        initPayDialogView(view);
        initData();
        setReadTheme(ReadThemeHelper.getReadTheme());
        if(activity != null && activity.mapContent.containsKey(sectionId)){
            contentBean = activity.mapContent.get(sectionId);
        }
        if(activity != null && activity.mapTopic.containsKey(sectionId)){
            topicBean = activity.mapTopic.get(sectionId);
            if (topicBean.getTags() != null && topicBean.getTags().length > 0)
            {
                tagsBeans = topicBean.getTags();
            }
            novelId = topicBean.getId();
            articleNum = Integer.valueOf(topicBean.getArticle_num());
            if (tagsBeans != null && tagsBeans.length > 0)
            {
                articleTitle = topicBean.getTitle();
                shareTitle = "【" + tagsBeans[0].getName() + "】" + topicBean.getTitle();
            }
        }

        if(contentBean == null){
            toGetNovelData();
        } else {
            if(!isLoginStateOld && AccountService.getInstance().isLogin() && contentBean.isNeed_pay()){
                if(activity != null && activity.mapContent.containsKey(sectionId)){
                    activity.mapContent.remove(sectionId);
                }
                if(activity != null && activity.mapTopic.containsKey(sectionId)){
                    activity.mapTopic.remove(sectionId);
                }
                toGetNovelData();
            }else if(activity.isAutoPay && contentBean.isNeed_pay()){
                if(activity != null && activity.mapContent.containsKey(sectionId)){
                    activity.mapContent.remove(sectionId);
                }
                if(activity != null && activity.mapTopic.containsKey(sectionId)){
                    activity.mapTopic.remove(sectionId);
                }
                toGetNovelData();
            }else{
                setContent();
            }
        }
        return view;
    }

    private TextView tvAllPrice;
    private LinearLayout llBuyAllTip;
    private FrameLayout btnPayAll;
    private LinearLayout llPayAllTip;
    private TextView tvPayAllTip;
    private TextView tvPayAllTipDesc;

    public Button getBtnPay() {
        return btnPay;
    }

    public LinearLayout getTvPayAllTip() {
        return llPayAllTip;
    }

    private ImageView ivLimitTime;
    private float lineSpace;

    private void initUI(View view) {
        lay = view.findViewById(R.id.lay);
        llHelp = (LinearLayout) view.findViewById(R.id.llHelp);
        ivHelp = (ImageView) view.findViewById(R.id.ivHelp);
        llHelp.setOnClickListener(this);
        viewPreview = view.findViewById(R.id.view_novel_section_preview);
        viewPreview.setOnClickListener(this);
        viewNext = view.findViewById(R.id.view_novel_section_next);
        viewNext.setOnClickListener(this);
        viewClick = view.findViewById(R.id.view_novel_details_list_item_click);
        viewClick.setOnClickListener(this);
        rlTop = (RelativeLayout) view.findViewById(R.id.rl_activity_novel_section_details_test_top);
        tvPageNumber = (TextView) view.findViewById(R.id.tvPageNumber);
        tvContent = (TextView) view.findViewById(R.id.novel_details_listitem_tx);
        progressBar = (ProgressBar) view.findViewById(R.id.iv_dialog_waiting);
        llLayout = (RelativeLayout) view.findViewById(R.id.ll_novel_details_list_item);
        llLayout.setOnClickListener(this);
        rlPay = (RelativeLayout) view.findViewById(R.id.rl_novel_details_list_item_pay);
        tvTip = (TextView) view.findViewById(R.id.tvTip);
        btnPay = (Button) view.findViewById(R.id.btn_bottom_novel_section_details_pay);
        btnPay.setOnClickListener(this);
        tvPayAllTip = (TextView) view.findViewById(R.id.tvPayAllTip);
        tvPayAllTipDesc = (TextView) view.findViewById(R.id.tvPayAllTipDesc);
        llPayAllTip = (LinearLayout) view.findViewById(R.id.llPayAllTip);
        btnPayAll = (FrameLayout) view.findViewById(R.id.btnPayAll);
        ivLimitTime = (ImageView) view.findViewById(R.id.ivLimitTime);
        btnPayAll.setOnClickListener(this);
        llBuyAllTip = (LinearLayout) view.findViewById(R.id.llBuyAllTip);
        tvAllPrice = (TextView) view.findViewById(R.id.tvAllPrice);
        llAutoPay = (LinearLayout) view.findViewById(R.id.ll_bottom_novel_section_details_auto_pay);
        llAutoPay.setOnClickListener(this);
        imgAutoPay = (ImageView) view.findViewById(R.id.img_novel_details_list_item_auto_pay);
        svLayout = (MyScrollView) view.findViewById(R.id.read_scrollview_id);
        svLayout.setOnScrollChangeListener(this);
        svLayout.setOnScrollToBottomListener(this);
        svLayout.setDetailsActivity(activity);
        vsNotNetwork = view.findViewById(R.id.vs_novel_details_list_item);
        btnReload = (Button) vsNotNetwork.findViewById(R.id.btn_common_novel_no_network);
        btnReload.setOnClickListener(this);
        mRedPacket = (ImageView) view.findViewById(R.id.novel_red_pocket);
        rlBottomStatus = (RelativeLayout) view.findViewById(R.id.rlBottomStatus);
        ivMobileStatus = (ImageView) view.findViewById(R.id.ivMobileBattry);
        ivCharger = (ImageView) view.findViewById(R.id.ivCharger);
        tvTime = (TextView) view.findViewById(R.id.tvTime);
        tvProgress = (TextView) view.findViewById(R.id.tvProgress);
        //读取字体设置
        if (activity != null) {
            mFontSize = activity.progressToFontSize(DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_FONT_SIZE_STATE,
                    activity, 1));
        }
        lineSpace = DiaoBaoSharedPreferences.getSharedPreferencesValueToFloat(SharedPreferencesKey.SP_READ_PAGE_READ_VERTICAL_SPACE,
                getActivity(), Constant.ReadSpace.NORMAL);
        tvContent.setLineSpacing(mFontSize,formatLineSpace(lineSpace));
    }

    /**
     * 缺钱弹窗初始化
     */
    private void initPayDialogView(View view){
        payDialogLayout = (RelativeLayout) view.findViewById(R.id.pay_dialog_layout);
        payCancelBtn = (TextView) view.findViewById(R.id.pay_cancel_btn);
        jumpToPayBtn = (TextView) view.findViewById(R.id.jump_to_pay_btn);
        payDesContentText = (TextView) view.findViewById(R.id.text_des_content);
        payDialogLayout.setOnClickListener(this);
        payCancelBtn.setOnClickListener(this);
        jumpToPayBtn.setOnClickListener(this);
    }

    public void setReadTheme(ReadTheme readTheme) {
        try {
            rlPay.setBackgroundColor(activity.getResources().getColor(R.color.transparent_background));
            if (tvPageNumber != null) {
                tvPageNumber.setTextColor(activity.getResources().getColor(readTheme.getStatusBarFontColor()));
                tvProgress.setTextColor(activity.getResources().getColor(readTheme.getStatusBarFontColor()));
                tvTime.setTextColor(activity.getResources().getColor(readTheme.getStatusBarFontColor()));
            }
            ReadBookUIUtil.setBtnUI(activity,btnPay,btnPayAll,llPayAllTip,tvPayAllTip,tvPayAllTipDesc);
            imgAutoPay.setImageResource(readTheme.getPayTheme().getIvAutoPayNone());
            tvAllPrice.setTextColor(activity.getResources().getColor(readTheme.getPayTheme().getDeleteLineFontColor()));
            ivHelp.setAlpha(readTheme.getPayTheme().getIvAlpha());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        updateFontSizeSelection(mFontSize);
    }


    public void setMobileState(MobileState mobileState) {
        if (mobileState != null) {
            if(ivMobileStatus!=null)
                ivMobileStatus.setImageResource(MobileState.getBatteryResource(mobileState));
            if (tvTime != null)
                tvTime.setText(mobileState.systemTime);
            if (ivCharger!=null) {
                if (mobileState.isCharger) {
                    ivCharger.setImageResource(ReadThemeHelper.getReadTheme().getBatteryTheme().getBatteryAdd());
                    ivCharger.setVisibility(View.VISIBLE);
                }else{
                    ivCharger.setVisibility(View.GONE);
                }
            }
        }
    }

    private String getProgressStr(int currChapter,int allChapter){
        StringBuilder sb = new StringBuilder();
        double progress = currChapter/((double)allChapter)*100;
        sb.append(PageFactory.formatDouble(progress)).append("%");
        return sb.toString();
    }


    private void initData() {
        Bundle bundle = getArguments();
        sectionId = bundle.getString(ARG_SECTION_id);
        offlineTopicData = bundle.getString(ARG_TOPIC);
        novelId = bundle.getString(ARG_NOVEL_ID);
        articleItem = bundle.getInt(ARG_ARTICLE_ITEM);
        try {
            if (activity != null &&
                    activity.articlesArray != null &&
                    activity.articlesArray.length() > articleItem - 1) {
                offlineData = activity.articlesArray.getJSONObject(articleItem - 1).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        allPage = bundle.getInt(ARG_ALL_PAGE);
        //获取上次阅读的id
        readID = sectionId;
        //小说浏览历史数据
        mRead_HirstoryUtil = new Read_HirstoryUtil(getActivity());
        // 获取屏幕宽度
        mScreenWidth = ScreenUtil.getScreenWidth(activity);
        mScreenHeight = ScreenUtil.getScreenHeight(activity);
        width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        height =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
    }

    public void updateOffLine(String offlineData,String offlineTopicData) {
        this.offlineTopicData = offlineTopicData;
        this.offlineData = offlineData;
        toGetNovelData();
    }

    private void toGetNovelData() {
        isLoginStateOld = AccountService.getInstance().isLogin();
        if (offlineData!=null) {
            //开启离线模式
            isOffLine = true;
            try {
                JSONObject offlineObj = new JSONObject(offlineData);
                //文件中读取小说json信息
                JSONObject topicObject = new JSONObject(offlineTopicData);
                if (topicBean == null)
                {
                    topicBean = new HomeTopBean();
                    topicBean.setJson2(topicObject);
                    if (topicBean.getTags() != null && topicBean.getTags().length > 0)
                    {
                        tagsBeans = topicBean.getTags();
                    }
                    try
                    {
                        articleNum = Integer.valueOf(topicBean.getArticle_num());
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    if (tagsBeans!= null && tagsBeans.length > 0)
                    {
                        articleTitle = topicBean.getTitle();
                        shareTitle = "【" + tagsBeans[0].getName() + "】" + topicBean.getTitle();
                    }
                    activity.mapTopic.put(sectionId, topicBean);
                }
                showOffLine(offlineObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            toSendRequestData();
        }
    }

    /**
     * 请求小说章节数据
     */
    public void toSendRequestData(){
        if(tvContent.getVisibility() == View.VISIBLE){
            tvContent.setVisibility(View.GONE);
        }
        if(progressBar.getVisibility() != View.VISIBLE){
            progressBar.setVisibility(View.VISIBLE);
        }
        if(rlPay.getVisibility() == View.VISIBLE){
            rlPay.setVisibility(View.GONE);
        }
        HomeMainServices.getInstance().loadNovelDetailsList(this, sectionId, 1);
    }

    /**
     * 设置标题栏
     * @param currentNum 当前页数
     * @param allNum 总页数
     * @param title 标题
     * @return
     */
    private String setSectionNameAndPageNum(int currentNum, int allNum, String title){
        StringBuffer sbSection = new StringBuffer();
        sbSection.append(currentNum);
        sbSection.append(".");
        sbSection.append(title);
        sbSection.append("(");
        sbSection.append(currentNum);
        sbSection.append("/");
        sbSection.append(allNum);
        sbSection.append("章)");
        return sbSection.toString();
    }

    /**
     * 展示离线内容
     */
    private void showOffLine(JSONObject mainObject) {
        contentBean = new HomeTopBean();
        contentBean.setJson(mainObject);
        activity.mapContent.put(sectionId, contentBean);
        setContent();
    }

    /**
     * 计算截取后的内容中是否有换行符，如果有，重新计算
     * @param content 截取后的内容
     * @param line 行数
     * @param linenumber 每行的字数
     * @return
     */
    private String removeLineString(String content, int line, int linenumber){
        StringBuffer sb = new StringBuffer();
        String str = content;
        int length = 0;
        for (int i = 0 ; i < 4 ; i++){
            int num = str.indexOf("\n");
            if(num > 0){
                line--;
                sb.append(str.substring(0, num+1));
                length = str.length() > linenumber * line ? linenumber * line : str.length();
                if(num + 1 < length){// 如果换行符的位置不大于剩余字符的数量
                    str = str.substring(num+1, length);
                }else{
                    str = str.substring(num+1, str.length());
                }
            }else{
                sb.append(str);
                break;
            }
        }
        return sb.toString();
    }

    /**
     * 设置小说内容
     */
    private void setContent(){
        setionTitle = contentBean.getTitle();
        tvPageNumber.setText(setSectionNameAndPageNum(articleItem, allPage, setionTitle));
        tvProgress.setText(getProgressStr(articleItem,allPage));
        int strsize = DensityUtil.sp2px(activity, mFontSize);// 计算当前字符大小(px)（粗略）
        int linenum = mScreenWidth / strsize;// 计算每行字符字数（粗略）
        /************ 获取要显示的章节内容 ***************/
        if(!TextUtils.isEmpty(contentBean.getEncrypt_content())){// 兼容旧版本，旧版本离线的小说并没有该字段，还需使用旧字段
            des = AesUtil.desEncrypt(contentBean.getEncrypt_content(), AesUtil.getMD5(contentBean.getKey()).substring(0, 16));
        }else{
            des = contentBean.getDes();
        }
        des = CacheManager.formatContent(des,indentType);
        des = des.replace("\n","\n\n");
        if(!TextUtil.isEmpty(des)&&contentBean != null){
            if (contentBean.isNeed_pay() || (isOffLine && contentBean.getArticle_status() == 0)) {
                if(des.length() > linenum * 4){
                    des = des.substring(0, linenum * 4);// 截取4行的字数
                }
                des = removeLineString(des, 4, linenum);// 计算内容内的换行符
            }
        }
        /************ 获取要显示的章节内容 ***************/
//        tvContent.setTypeface(Typeface.SANS_SERIF);
        styledText = new SpannableString(setionTitle + "\n\n" + des);
        updateFontSizeSelection(mFontSize);
        llLayout.measure(width,height);
        if(llLayout.getMeasuredHeight() > mScreenHeight / 2){// 当文本内容的父布局超过半屏时，去除中间点击布局，否则显示
            viewClick.setVisibility(View.GONE);
        }else{
            viewClick.setVisibility(View.VISIBLE);
        }
        if(activity != null){
            System.out.println("离线更新index="+(articleItem-1));
            activity.toGetCommentData(articleItem - 1);
        }
        if(contentBean != null){
            if (isOffLine) {
                getOfflineLayout(contentBean.getArticle_status()== 0);
            }else{
                setIsPay(!contentBean.isNeed_pay());
            }
        }
        initScrollviewMove();
    }

    /**
     * 设置字体大小
     */
    public void updateFontSizeSelection(int fontSize) {
        mFontSize = fontSize;
//        if (tvContent != null) {
//            tvContent.setTypeface(Typeface.SANS_SERIF);
//        }
        if (activity == null) {
            return;
        }
        if (tvContent != null && styledText != null){
            ColorStateList titleColor = ColorStateList.valueOf(activity.getResources().getColor(ReadThemeHelper.getReadTheme().getTitleFontColor()));
            ColorStateList contentColor = ColorStateList.valueOf(activity.getResources().getColor(ReadThemeHelper.getReadTheme().getContentFontColor()));
            styledText.setSpan(new TextAppearanceSpan("",Typeface.NORMAL, PageFactory.getTitleFontSize(fontSize),titleColor,titleColor),0, setionTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            styledText.setSpan(new TextAppearanceSpan("",Typeface.NORMAL,fontSize,contentColor,contentColor), setionTitle.length(), setionTitle.length()+des.length()+2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvContent.setText(styledText, TextView.BufferType.SPANNABLE);
            tvContent.setLineSpacing(mFontSize,formatLineSpace(lineSpace));
        }
    }

    public void setLineSpace(float lineSpace) {
        this.lineSpace = lineSpace;
        if (tvContent != null) {
            tvContent.setLineSpacing(mFontSize,formatLineSpace(lineSpace));
        }
    }

    private float formatLineSpace(float lineSpace) {
        if (lineSpace == Constant.ReadSpace.LOOSE) {
            return 0.7f;
        } else if(lineSpace == Constant.ReadSpace.TIGHT){
            return 0.2f;
        }else{
            return 0.5f;
        }
    }

    public void setIndent(int indentType) {
        if (tvContent != null){
            des = CacheManager.formatContent(des,indentType);
            des = des.replace("\n","\n\n");
            /************ 获取要显示的章节内容 ***************/
//            tvContent.setTypeface(Typeface.SANS_SERIF);
            styledText = new SpannableString(setionTitle + "\n\n" + des);
            ColorStateList titleColor = ColorStateList.valueOf(activity.getResources().getColor(ReadThemeHelper.getReadTheme().getTitleFontColor()));
            ColorStateList contentColor = ColorStateList.valueOf(activity.getResources().getColor(ReadThemeHelper.getReadTheme().getContentFontColor()));
            styledText.setSpan(new TextAppearanceSpan("",Typeface.NORMAL, PageFactory.getTitleFontSize(mFontSize),titleColor,titleColor),0, setionTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            styledText.setSpan(new TextAppearanceSpan("",Typeface.NORMAL,mFontSize,contentColor,contentColor), setionTitle.length(), setionTitle.length()+des.length()+2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvContent.setText(styledText, TextView.BufferType.SPANNABLE);
        }
    }

    /**
     * 加载订阅布局
     * @param isPaid 是否支付过
     */
    private void setIsPay(boolean isPaid){
        isPay = isPaid;
        if(isPaid){
            if(rlPay.getVisibility() == View.VISIBLE){
                rlPay.setVisibility(View.GONE);
            }
        }else{
            setPayLayout();
        }
    }

    private void getOfflineLayout(boolean isShow) {
        if (isShow) {
            if(llAutoPay.getVisibility() == View.VISIBLE){
                llAutoPay.setVisibility(View.INVISIBLE);
            }
            rlPay.setVisibility(View.VISIBLE);
            btnPay.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor()));
            btnPay.setBackgroundResource(ReadThemeHelper.getReadTheme().getPayTheme().getBtnBg());
            btnPay.setVisibility(View.VISIBLE);
            btnPayAll.setVisibility(View.INVISIBLE);
            llBuyAllTip.setVisibility(View.INVISIBLE);
            tvTip.setText("本章节未离线，请离线后阅读");
            btnPay.setText("马上下载");
        }else{
            rlPay.setVisibility(View.GONE);
        }
    }

    String tip = "";
    /**
     * 设置付费布局
     */
    public void setPayLayout(){
        if(rlPay.getVisibility() != View.VISIBLE){
            rlPay.setVisibility(View.VISIBLE);
        }
        ivLimitTime.setVisibility(View.GONE);
        if (AccountService.getInstance().isLogin()){// 已登录
            ReadBookUIUtil.setPayLayout(activity,topicBean,contentBean,btnPayAll,llBuyAllTip,tvTip,btnPay,ivLimitTime,llPayAllTip,tvPayAllTip,tvPayAllTipDesc,llAutoPay,tvAllPrice);
        } else {// 未登录
            if(llAutoPay.getVisibility() == View.VISIBLE){
                llAutoPay.setVisibility(View.INVISIBLE);
            }
            btnPay.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor()));
            btnPay.setBackgroundResource(ReadThemeHelper.getReadTheme().getPayTheme().getBtnBg());
            btnPayAll.setVisibility(View.INVISIBLE);
            llBuyAllTip.setVisibility(View.GONE);
            btnPay.setText(activity.getResources().getString(R.string.login_go_logged));
        }
    }

    /**
     *  记录看过的小说章节id
     */
    public void toReadInsert(){
        if (!TextUtils.isEmpty(readID))
        {
            mRead_HirstoryUtil.insertHirstory(novelId, readID);
        }
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (handleType == HomeMainServices.HANDLE_TYPE_NOVEL_PAY_ALL_URL){
            //loading状态恢复
            if (response.getStatus() == 0 && response.getFail_code() == 0) {
                toSendRequestData();
                activity.toReloadPreviewAndNextData();
                activity.synchorizontaldata(sectionId);
//                Toast.makeText(getActivity(), "购买成功", Toast.LENGTH_LONG).show();
                return;
            }
            btnPay.setClickable(true);
            btnPayAll.setClickable(true);
        }
        isPaying = false;
        if(progressBar.getVisibility() == View.VISIBLE){
            progressBar.setVisibility(View.GONE);
        }
        if(tvContent.getVisibility() != View.VISIBLE){
            tvContent.setVisibility(View.VISIBLE);
        }
        if(response.getStatus() == 0 && response.getFail_code() == 0){
            if(vsNotNetwork.getVisibility() == View.VISIBLE){
                vsNotNetwork.setVisibility(View.GONE);
            }
            try {
                JSONObject jsonObject = (JSONObject) response.getData();
                switch (handleType){
                    // 章节文字数据
                    case HomeMainServices.HANDLE_TYPE_LOAD_NOVEL_DETAILS:
                        activity.showHint();
                        toHandleData(jsonObject,false);
                        break;
                    case HomeMainServices.HANDLE_TYPE_BUY_CHARTER:// 购买章节
                        activity.toReloadPreviewAndNextData();
                        toHandleData(jsonObject,true);
                        if(isAutoPay){
                            HomeMainServices.getInstance().getAutoPay(this, novelId);// 自动订阅
                            activity.toReloadPreviewAndNextData();
                        }else{
                            activity.synchorizontaldata(sectionId);
                        }
                        break;
                    case HomeMainServices.HANDLE_TYPE_AUTO_PAY:// 自动订阅
//                        activity.toReloadSectionData();
                        break;
                    default:
                        break;
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        } else {
            if(handleType == HomeMainServices.HANDLE_TYPE_BUY_CHARTER && response.getStatus() == 32){
                if (!payDialogLayout.isShown()){
                    TMAnalysis.event(activity , "3_7_Novelreading_purchase_section_Recharge");
                    payDialogLayout.setVisibility(View.VISIBLE);
                    payDesContentText.setText(response.getUser_msg());
                    return;
                }
            }
            NoRepeatToast.setToast(getActivity(), DiaobaoUtil.getErrorTips(response)).show();
            if(handleType == HomeMainServices.HANDLE_TYPE_LOAD_NOVEL_DETAILS && !isOffLine && vsNotNetwork.getVisibility() != View.VISIBLE){
                vsNotNetwork.setVisibility(View.VISIBLE);
                if(activity != null){
                    if(activity.isTopAndBottomVisiable){
                        activity.hideMenu();
                    }
                }
            }
        }
    }

    public void showTip(){
        if (topicBean != null) {
            String tip = topicBean.getTipinfo();
            if (!TextUtils.isEmpty(tip) && !tip.equals("null")) {
                if (topicBean.isVipFree()){
                    String key = "show_tip_"+novelId;
                    boolean isCanShow = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(key, getActivity(), true);
                    if (isCanShow) {
                        DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(key,false,getActivity());
                        topicBean.setTipinfo("");
                        Toast.makeText(getActivity(),tip,Toast.LENGTH_LONG).show();
                    }
                }else{
                    topicBean.setTipinfo("");
                    Toast.makeText(getActivity(),tip,Toast.LENGTH_LONG).show();
                }

            }
        }
    }

    private void toHandleData(JSONObject jsonObject,boolean isPay) throws Exception{
        // details
        JSONObject detail = jsonObject.getJSONObject("detail");
        contentBean = new HomeTopBean();
        contentBean.setJson(detail);
        if (isPay && !contentBean.isNeed_pay()) {  //购买章节后获得数据
            try {
                activity.setSurplusTotal(Integer.parseInt(contentBean.getSpend_num()));
            } catch (Exception e) {
            }
        }

        activity.getPayInfo();
        // topic
        if (topicBean == null)
        {
            JSONObject topicObject = jsonObject.getJSONObject("topic");
            topicBean = new HomeTopBean();
            topicBean.setJson2(topicObject);
            setTipData(jsonObject);

            if (topicBean.getTags() != null && topicBean.getTags().length > 0)
            {
                tagsBeans = topicBean.getTags();
            }
            novelId = topicBean.getId();
            articleNum = Integer.valueOf(topicBean.getArticle_num());
            if (tagsBeans != null && tagsBeans.length > 0)
            {
                articleTitle = topicBean.getTitle();
                shareTitle = "【" + tagsBeans[0].getName() + "】" + topicBean.getTitle();
            }
            activity.mapTopic.put(sectionId, topicBean);
        }else {
            setTipData(jsonObject);
        }
        activity.mapContent.put(sectionId, contentBean);

        /**
         * 显示解析后的json数据
         */
        setContent();
        //get red pocket data
        if (! detail.isNull("red_envelope")) {
            JSONObject red_pocket = detail.getJSONObject("red_envelope");
            redPocketStr = red_pocket;
            String redStatusPocket = red_pocket.getString("status");
            String reUserStatus = red_pocket.getString("user_status");
            
            if (redStatusPocket.equals("1") && (reUserStatus.equals("0") || reUserStatus.equals("2")  )) {//todo
                isShowRedPacket = true;
            }else {
                isShowRedPacket = false;
                if(mRedPacket != null){
                    mRedPacket.setVisibility(View.INVISIBLE);
                }
            }
        }else {
            isShowRedPacket = false;
            if(mRedPacket != null){
                mRedPacket.setVisibility(View.INVISIBLE);
            }

        }
    }


    private void setTipData(JSONObject jsonObject)throws Exception{
        if (jsonObject.has("tipinfo")){
            topicBean.setTipinfo(jsonObject.getString("tipinfo"));
        }
        if (!topicBean.isVipFree()){
            String key = "show_tip_"+novelId;
            boolean isCanShow = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(key, getActivity(), false);
            if (!isCanShow) {
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(key,true,getActivity());
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activity = null;
    }

    /** 返回章节title */
    public String getArticleTitle(){
        return articleTitle;
    }

    public HomeTopBean getTopicBean(){
        return topicBean;
    }

    public int getArticleItem(){
        return articleItem;
    }

    public int getRealIdsPos(){
        return articleItem-1;
    }

    public HomeTopBean getContentBean(){
        return contentBean;
    }

    /** 返回章节id */
    public String getSectionId(){
        return sectionId;
    }

    public void pageUp() {
        if (activity != null) {
            activity.isClickNOrPScroll = false;
            svLayout.smoothScrollTo(nowY, nowY-mScreenHeight+350);
        }
    }

    public void pageDown() {
        if (activity != null) {
            activity.isClickNOrPScroll = false;
            svLayout.smoothScrollTo(nowY, nowY+mScreenHeight-350);
        }
    }

    public void buyChapter() {
        if(!isPaying){
            isPaying = true;
            TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section");
            int read_ticket_id = 0;
            if (activity.getPayInfoBean()!=null && activity.getPayInfoBean().getReadTicketInfo()!=null &&
                    activity.getPayInfoBean().getReadTicketInfo().getId() > 0) {
                read_ticket_id = activity.getPayInfoBean().getReadTicketInfo().getId();
                QLXNotificationCenter.getInstance().postNotify("TFMyTicketNumChangeNotify",null);

            }
            HomeMainServices.getInstance().getBuyCharter(this, sectionId,read_ticket_id);// 购买章节
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnPayAll://完本购买
                if (isYouthModel) {
                    Toast.makeText(getActivity(),"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                btnPay.setClickable(false);
                btnPayAll.setClickable(false);
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_BUY_FULL_NOVEL,novelId);
                if (tvPayAllTip.getText().toString().contains("完本")){
                    HomeMainServices.getInstance().loadPayAllNovel(this, novelId);
                }else{  //剩余章节购买
                    HomeMainServices.getInstance().loadPayVerbNovel(this, novelId);
                }
                break;
            case R.id.view_novel_section_next:
                pageDown();
                break;
            case R.id.view_novel_section_preview:
                pageUp();
                break;
            case R.id.view_novel_details_list_item_click:
            case R.id.ll_novel_details_list_item:// 整体布局
                if(activity != null){
                    activity.isClickNOrPScroll = false;
                    if(activity.isTopAndBottomVisiable || activity.isSecondMuneVisiable){
                        activity.hideMenu();
                    }else{
                        activity.showFirstMenu();
                    }
                }
                break;
            case R.id.btn_bottom_novel_section_details_pay:// 订阅按钮
                if (isYouthModel) {
                    Toast.makeText(getActivity(),"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                if (isOffLine) {
                    String url =  "TFNovel/TFOffLine.js?present=1&read=true&id=" +novelId;
                    DiaobaoBaseActivity activity = (DiaobaoBaseActivity) getActivity();
                    activity.presentWeexView(url);
                }else{
                    if(!AccountService.getInstance().isLogin()){// 判断是否已登录，如果未登录，则去登录
                        TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section_Signin");
                        AccountService.getInstance().jumpToLogin();
                        return;
                    }
                    buyChapter();
                }
                break;
            case R.id.ll_bottom_novel_section_details_auto_pay:// 自动订阅
                if(isAutoPay){
                    imgAutoPay.setImageResource(ReadThemeHelper.getReadTheme().getPayTheme().getIvAutoPayNone());
                }else{
                    imgAutoPay.setImageResource(ReadThemeHelper.getReadTheme().getPayTheme().getIvAutoPaySelect());
                    TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section_Continuouspurchase");
                }
                isAutoPay = !isAutoPay;
                activity.isAutoPay = isAutoPay;
                break;
            case R.id.btn_common_novel_no_network:// 重新加载
                if(progressBar.getVisibility() != View.VISIBLE){
                    progressBar.setVisibility(View.VISIBLE);
                }
                vsNotNetwork.setVisibility(View.GONE);
                HomeMainServices.getInstance().loadNovelDetailsList(this, sectionId, 1);
                break;
            case R.id.pay_cancel_btn:
                if (payDialogLayout.isShown()){
                    payDialogLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.jump_to_pay_btn:
                TMAnalysis.event(activity , "jump_to_pay");
                GiftService.enterPayWebActivity(activity);
                break;
            case R.id.llHelp:
                if (activity != null) {
                    activity.showBuyTipDialog();
                }
                break;
            default:
                break;
        }
    }

    private static final String TAG = SectionDetailsFragment.class.getSimpleName();
    @Override
    public void onScrollChange(int l, int t, int oldl, int oldt) {
        nowY = t;
        if (activity != null) {
            activity.setVerticalY(nowY);
        }
        viewPreview.layout(0, t, mScreenWidth, t+(mScreenHeight/3) - 50);
        viewNext.layout(0, t+(mScreenHeight/2) + 200, mScreenWidth, t+mScreenHeight);
        if(activity != null){
            if((activity.isTopAndBottomVisiable||activity.isSecondMuneVisiable) && !activity.isClickNOrPScroll && !activity.isHintShow()){
                activity.hideMenu();
            }
        }
    }

    public static final int HANDLER_SCROLLVIEW_MOVE = 1;
    Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case HANDLER_SCROLLVIEW_MOVE:
                    if(nowY > 0){
                        svLayout.smoothScrollTo(nowY, nowY-1);
                    }
//                    else{
//                        svLayout.smoothScrollTo(nowY, nowY+1);
//                    }
                    break;
            }
        }
    };



    //是否已经进行过初始化了
    private boolean hasInitScrollviewMove = false;

    private void initScrollviewMove(){
        if (hasInitScrollviewMove){
            return;
        }

        hasInitScrollviewMove = true;
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = HANDLER_SCROLLVIEW_MOVE;
                handler.sendMessage(msg);
                timer.cancel();
            }
        }, 500);
    }


    @Override
    public void onScrollToBottom() {

        if (isShowRedPacket) {
            mRedPacket.setVisibility(View.VISIBLE);
            mRedPacket.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        //mRedPacket.setImageResource(R.drawable.red_read_open);
                        if (topicBean != null && redPocketStr != null) {
                            topicTitle = topicBean.getTitle();
                            redPocketStr.put("title",topicTitle);
                            redPocketStr.put("position","read");

                            String jsonStr = redPocketStr.toString();
                            String encodeJsonStr = URLEncoder.encode(jsonStr,"utf8");

                            String url =  "TFRedEnvelope/TFREStatus.js?present=1&needLogin=1&position=read" + "&data=" + encodeJsonStr;


                            DiaobaoBaseActivity activity = (DiaobaoBaseActivity) getActivity();
                            activity.presentWeexView(url);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                }
            });
        }

    }
}
